/**
 * 
 */
package com.edu.lawdoc.api.controller.assistor;

import java.util.HashMap;
import java.util.Iterator;
import java.util.List;
import java.util.Map;
import java.util.Map.Entry;

import com.baymax.validator.engine.ValidatorEngine;
import com.edu.lawdoc.api.utils.ArrayKit;
import com.edu.lawdoc.api.utils.LoggerKit;
import com.edu.lawdoc.errors.AppException;
import com.edu.lawdoc.errors.Errors;
import com.fasterxml.jackson.core.JsonProcessingException;
import com.fasterxml.jackson.core.type.TypeReference;
import com.fasterxml.jackson.databind.JsonMappingException;
import com.fasterxml.jackson.databind.ObjectMapper;

/**
 * @author xiao.hu
 *
 */
public class ParamAssistor {
	static ObjectMapper mapper = new ObjectMapper();
	
	public static String toStr(Object o) {
		return o == null ? "" : o.toString().trim();
	}
	
	public static String wrapVague(String v) {
		return "%" + v + "%";
	}
	
	public static String wrapRightVague(String v) {
		return v + "%";
	}

	public static Map<String, Object> arrangeParamAxois(String formData, String keyPrefix) {
		return arrangeParamAxois(formData, keyPrefix, null);
	}
	
	/**
	 * 只支持简单的json
	 * @param keyPrefix
	 * @return
	 * @throws JsonProcessingException 
	 * @throws JsonMappingException 
	 */
	public static Map<String, Object> arrangeParamAxois(String formData, String keyPrefix, String[] exception) {
		Map<String, Object> paraJsonMap;
		try {
			paraJsonMap = mapper.readValue(formData, new TypeReference<HashMap<String, Object>>() {});
		} catch (JsonProcessingException e) {
			throw new AppException(Errors.JSON_PROCESSING_EXCEPTION.name(),
					String.format("(formData: %s)", formData),
					e.getMessage());
		}

		Map<String, Object> paragraphParamsMap = new HashMap<> ();
		
		/* 遍历paraJsonMap */
		Iterator<Entry<String, Object>> it = paraJsonMap.entrySet().iterator();
		while(it.hasNext()) {
			Entry<String, Object> entry = it.next();
			
			/* 取得每一项键值 */
			String key = entry.getKey();
			Object value = entry.getValue();
			
			LoggerKit.debug("key: %s, parameterValue: %s", key, value);
			
			/* 如果keyPrefix不为null, 并且未被列入排除列表时 则增加这个前缀给key */
			String newKey = (keyPrefix == null || ArrayKit.contains(exception, key)) ? key : (keyPrefix + "." + key);

			if (!ArrayKit.contains(exception, key)) {
				if (!(value instanceof List)) {
					/* 校验 */
					validate(newKey, value);
				} else {
					List<Object> enumValues = (List<Object>) value;
					for (Object val : enumValues) {
						/* 校验 */
						validate(newKey, val);
					}
				}

			}

			paragraphParamsMap.put(key, value);
		}
		
		return paragraphParamsMap;
	}

	private static void validate(String newKey, Object value) {
		String valueForValidator = toStr(value);
		/* 校验 */
		boolean isOK = ValidatorEngine.INSTANCE.validate(newKey, valueForValidator);
		if (!isOK) {
			throw new AppException(Errors.ILLEGAL_PARAMETER.name(),
					String.format("(Validate key: %s, value: %s)", newKey, valueForValidator),
					"Illegal parameter");
		}
	}
}
